package com.guaoran.utils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;


public class Response {
	private HttpsURLConnection con;
	private int status;
	private InputStream is;
	private String responseAsString = null;
	private boolean streamConsumed = false;
	private HttpURLConnection httpcon;

	public Response() {
	}

	public Response(HttpsURLConnection con) throws IOException {
		this.con = con;
		this.status = con.getResponseCode();
		if (null == (this.is = con.getErrorStream())) {
			this.is = con.getInputStream();
		}
	}
	
	public Response(HttpURLConnection httpcon) throws IOException {
		this.httpcon = httpcon;
		this.status = httpcon.getResponseCode();
		if ((this.is = httpcon.getErrorStream()) == null){
			this.is = httpcon.getInputStream();
		}
	}

	public InputStream asStream() {
		if (this.streamConsumed) {
			throw new IllegalStateException("Stream has already been consumed.");
		}
		return this.is;
	}

	public String asString() throws Exception {
		if (null == this.responseAsString)
			try {
				InputStream stream = asStream();
				if (null == stream) {
					return null;
				}
				BufferedReader br = new BufferedReader(new InputStreamReader(
						stream, "UTF-8"));
				StringBuilder buf = new StringBuilder();
				String line;
				while (null != (line = br.readLine())) {
					buf.append(line).append("\n");
				}
				this.responseAsString = buf.toString();
				stream.close();
				if (this.con != null) {
					this.con.disconnect();
				}
				if (this.httpcon != null) {
					this.httpcon.disconnect();
				}
				this.streamConsumed = true;
			} catch (NullPointerException npe) {
				throw new Exception(npe.getMessage(), npe);
			} catch (IOException ioe) {
				throw new Exception(ioe.getMessage(), ioe);
			}

		return this.responseAsString;
	}

	public int getStatus() {
		return this.status;
	}
}